//
//  JCLUserAccountModel.swift
//  WeiBo
//
//  Created by DDC on 2017/9/13.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

//获取授权信息模型
class JCLUserAccountModel: NSObject {

    //accessToken
    var access_token:String? //= "2.00Zzp2lBGCpNlB55de7a7a2eiicJLD"
    //过期时间
    var expires_in:TimeInterval = 0 {
        
        didSet {
            
            expiresDate = Date.init(timeIntervalSinceNow: expires_in)
        }
    }
    //uid
    var uid: String?
    //过期日期
    var expiresDate:Date?
    
    //用户昵称
    var screen_name:String?
    //用户头像
    var avatar_large:String?
    
    
    override var description: String
        {
        return yy_modelDescription()
    }
    
    //保存数据方法
    func saveAccount() {
        
        var dict = (yy_modelToJSONObject() as? [String:Any]) ?? [:]
        
        //删除不需要的属性
        dict.removeValue(forKey: "expires_in")
        
        //守护data一定有值
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
        else {
            return
        }
        //保存路径
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("userAccount.json")
        
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print(filePath)
     
        
    }
    
    //从沙盒加载数据显示登录界面
    override init() {
        super.init()
        
        //获取沙盒路径
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("userAccount.json")
        guard  let data = NSData(contentsOfFile: filePath) else {
            return
        }
        
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:Any]
        
        /// 为登录信息赋值
        /// ***最为关键的 登录界面/授权界面的切换
        yy_modelSet(with: (dict ?? [:])!)
        print("从沙盒获取登录信息\(self)")
        
        //测试过期日期
        //expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        if expiresDate?.compare(Date()) != .orderedDescending {
            //过期
            access_token = nil
            uid = nil
            //删除文件
           try? FileManager.default.removeItem(atPath: filePath)
            print("账户过期\(self) ---\(filePath)  ")
        }
    }
}



